<?php

namespace App\Livewire;

use BaconQrCode\Renderer\Image\SvgImageBackEnd;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
use Filament\Actions\Concerns\InteractsWithActions;
use Filament\Actions\Contracts\HasActions;
use Filament\Facades\Filament;
use Filament\Forms\Components\Select;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Illuminate\View\View;
use Livewire\Component;
use Filament\Actions\Action;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
use App\Models\Project;
use App\Models\User;

class UserStat extends Component implements HasForms, HasActions
{
    use InteractsWithActions, InteractsWithForms;
    public function render():View
    {
        $my_project_count = Project::where('user_id', Filament::auth()->id())->count();
        $my_balance = User::find(Filament::auth()->id())->balance;

        $widgets = [
            [
                'icon' => '',
                'title' => '我的余额',
                'balance' => $my_balance,
                'description' => '当前余额',
                'button_label' => '充值',
            ],
            [
                'icon' => '',
                'title' => '我的项目',
                'balance' => $my_project_count,
                'description' => '当前余额',
                'button_label' => '列表'
            ],
            [
                'icon' => '',
                'title' => '我的套餐',
                'balance' => '500',
                'description' => '当前余额'
            ],
            [
                'icon' => '',
                'title' => '我的邀请',
                'balance' => '0',
                'description' => '(到期：2025-08-01)'
            ]
        ];
        return view('livewire.user-stat', compact('widgets'));
    }

    public function rechargeAction()
    {
        return Action::make('recharge')
            ->requiresConfirmation()
            ->modalHeading('充值')
            ->modalDescription('请选择充值金额')
            ->label('充值');
    }

    public function createProject():Action
    {
        return Action::make('createProject')
            ->label('创建项目')
            ->modalHeading('创建项目')
            ->modalWidth('md')
            ->form([
                TextInput::make('title')
                    ->label('项目名称')
                    ->required(),
                Textarea::make('description')
                    ->label('项目描述')
                    ->required(),
                Select::make('project_type')
                    ->label('项目类型')
                    ->options(
                        [
                            'react' => 'react',
                            'next' => 'next',
                            'vue' => 'vue',
                            'nuxt' => 'nuxt',
                            'blade' => 'blade',
                        ]
                    )
            ])
            ->action(function (array $data):void {

                $title = $data['title'];
                $description = $data['description'];
                $project_type = $data['project_type'];

                $project = Project::create([
                    'title' => $title,
                    'description' => $description,
                    'project_type' => $project_type,
                    'user_id' => Filament::auth()->id(),
                ]);

                $source_folder = storage_path('app/project-templates/'.$project_type);

                $storage_folder = storage_path('app/projects/'.auth()->id().'/'.$project->project_type.'/'.$project->id).'/src';

                if (!is_dir($storage_folder)) {
                    mkdir($storage_folder, 0755, true);

                    //$this->copyAllFiles($source_folder, $storage_folder);
                }

                Notification::make()
                    ->title('保存成功！')
                    ->success()
                    ->send();
            });
    }


    function copyAllFiles($sourceDir, $destinationDir)
    {
        // Ensure source directory exists
        if (!is_dir($sourceDir)) {
            throw new Exception("Source directory does not exist: $sourceDir");
        }

        // Create destination directory if it doesn't exist
        if (!is_dir($destinationDir)) {
            mkdir($destinationDir, 0755, true);
        }

        // Scan files
        $files = scandir($sourceDir);
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') {
                continue;
            }

            $srcFile = rtrim($sourceDir, '/') . '/' . $file;
            $destFile = rtrim($destinationDir, '/') . '/' . $file;

            // Only copy files (skip directories)
            if (is_file($srcFile)) {
                copy($srcFile, $destFile);
            }
        }
    }



    public function renewPlan():Action
    {
        return Action::make('renewPlan')
            ->label('续费套餐');
    }

    public function invite():Action
    {
        $renderer = new ImageRenderer(
            new RendererStyle(150, 1),
            new SvgImageBackEnd()
        );
        $writer = new Writer($renderer);
        $referralLink = route('filament.user.auth.register'). "?refer=".Filament::auth()->getUser()->referral_code;
        $qrcode = $writer->writeString($referralLink);
        $qrcode = str_replace('<?xml version="1.0" encoding="UTF-8"?>', "", $qrcode);
        return Action::make('invite')
            ->label('邀请好友')
            ->modalHeading('邀请好友')
            ->modalContent(fn (): View => view(
                'livewire.referral-list',
                    [
                        "referralLink" => $referralLink,
                        "qrcode" => $qrcode,
                    ]
            ))->modalSubmitAction(false)
            ->modalCancelActionLabel('关闭')
            ->modalFooterActionsAlignment('right');
    }

}
